"use client"

import { useState, useEffect } from "react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { Checkbox } from "@/components/ui/checkbox"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { Badge } from "@/components/ui/badge"
import { X, Plus } from "lucide-react"
import type { Contact } from "./columns"

interface ContactFormProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  contact?: Contact | null
  onSave: (contact: Omit<Contact, 'id' | 'created_at' | 'updated_at'>) => Promise<void>
  groups: string[]
  tags: string[]
}

export function ContactForm({ open, onOpenChange, contact, onSave, groups }: ContactFormProps) {
  const [formData, setFormData] = useState({
    name: "",
    phone: "",
    email: "",
    address: "",
    company: "",
    position: "",
    notes: "",
    tags: [] as string[],
    birthday: "",
    group: "默认",
    is_favorite: false,
    avatar: "",
    social_accounts: {} as Record<string, string>,
  })
  const [newTag, setNewTag] = useState("")
  const [newSocialKey, setNewSocialKey] = useState("")
  const [newSocialValue, setNewSocialValue] = useState("")
  const [loading, setLoading] = useState(false)

  // 重置表单数据
  const resetForm = () => {
    setFormData({
      name: "",
      phone: "",
      email: "",
      address: "",
      company: "",
      position: "",
      notes: "",
      tags: [],
      birthday: "",
      group: "默认",
      is_favorite: false,
      avatar: "",
      social_accounts: {},
    })
    setNewTag("")
    setNewSocialKey("")
    setNewSocialValue("")
  }

  // 当联系人数据变化时更新表单
  useEffect(() => {
    if (contact) {
      setFormData({
        name: contact.name || "",
        phone: contact.phone || "",
        email: contact.email || "",
        address: contact.address || "",
        company: contact.company || "",
        position: contact.position || "",
        notes: contact.notes || "",
        tags: contact.tags || [],
        birthday: contact.birthday ? contact.birthday.split('T')[0] : "",
        group: contact.group || "默认",
        is_favorite: contact.is_favorite || false,
        avatar: contact.avatar || "",
        social_accounts: contact.social_accounts || {},
      })
    } else {
      resetForm()
    }
  }, [contact])

  // 当对话框关闭时重置表单
  useEffect(() => {
    if (!open) {
      resetForm()
    }
  }, [open])

  const handleInputChange = (field: string, value: string | boolean) => {
    setFormData(prev => ({
      ...prev,
      [field]: value
    }))
  }

  const addTag = () => {
    if (newTag.trim() && !formData.tags.includes(newTag.trim())) {
      setFormData(prev => ({
        ...prev,
        tags: [...prev.tags, newTag.trim()]
      }))
      setNewTag("")
    }
  }

  const removeTag = (tagToRemove: string) => {
    setFormData(prev => ({
      ...prev,
      tags: prev.tags.filter(tag => tag !== tagToRemove)
    }))
  }

  const addSocialAccount = () => {
    if (newSocialKey.trim() && newSocialValue.trim()) {
      setFormData(prev => ({
        ...prev,
        social_accounts: {
          ...prev.social_accounts,
          [newSocialKey.trim()]: newSocialValue.trim()
        }
      }))
      setNewSocialKey("")
      setNewSocialValue("")
    }
  }

  const removeSocialAccount = (key: string) => {
    setFormData(prev => {
      const newSocialAccounts = { ...prev.social_accounts }
      delete newSocialAccounts[key]
      return {
        ...prev,
        social_accounts: newSocialAccounts
      }
    })
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    
    if (!formData.name.trim()) {
      alert("姓名不能为空")
      return
    }

    setLoading(true)
    try {
      await onSave(formData)
      onOpenChange(false)
    } catch (error) {
      console.error("保存失败:", error)
      alert("保存失败，请重试")
    } finally {
      setLoading(false)
    }
  }

  const handleKeyPress = (e: React.KeyboardEvent, action: () => void) => {
    if (e.key === 'Enter') {
      e.preventDefault()
      action()
    }
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>
            {contact ? "编辑联系人" : "新建联系人"}
          </DialogTitle>
          <DialogDescription>
            {contact ? "修改联系人信息" : "添加新的联系人信息"}
          </DialogDescription>
        </DialogHeader>

        <form onSubmit={handleSubmit} className="space-y-6">
          {/* 基本信息 */}
          <div className="space-y-4">
            <h3 className="text-lg font-medium">基本信息</h3>
            
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="name">姓名 *</Label>
                <Input
                  id="name"
                  value={formData.name}
                  onChange={(e) => handleInputChange("name", e.target.value)}
                  placeholder="请输入姓名"
                  required
                />
              </div>
              
              <div className="space-y-2">
                <Label htmlFor="phone">电话</Label>
                <Input
                  id="phone"
                  value={formData.phone}
                  onChange={(e) => handleInputChange("phone", e.target.value)}
                  placeholder="请输入电话号码"
                />
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="email">邮箱</Label>
                <Input
                  id="email"
                  type="email"
                  value={formData.email}
                  onChange={(e) => handleInputChange("email", e.target.value)}
                  placeholder="请输入邮箱地址"
                />
              </div>
              
              <div className="space-y-2">
                <Label htmlFor="birthday">生日</Label>
                <Input
                  id="birthday"
                  type="date"
                  value={formData.birthday}
                  onChange={(e) => handleInputChange("birthday", e.target.value)}
                />
              </div>
            </div>

            <div className="space-y-2">
              <Label htmlFor="address">地址</Label>
              <Input
                id="address"
                value={formData.address}
                onChange={(e) => handleInputChange("address", e.target.value)}
                placeholder="请输入地址"
              />
            </div>
          </div>

          {/* 工作信息 */}
          <div className="space-y-4">
            <h3 className="text-lg font-medium">工作信息</h3>
            
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="company">公司</Label>
                <Input
                  id="company"
                  value={formData.company}
                  onChange={(e) => handleInputChange("company", e.target.value)}
                  placeholder="请输入公司名称"
                />
              </div>
              
              <div className="space-y-2">
                <Label htmlFor="position">职位</Label>
                <Input
                  id="position"
                  value={formData.position}
                  onChange={(e) => handleInputChange("position", e.target.value)}
                  placeholder="请输入职位"
                />
              </div>
            </div>
          </div>

          {/* 分组和标签 */}
          <div className="space-y-4">
            <h3 className="text-lg font-medium">分组和标签</h3>
            
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="group">分组</Label>
                <Select value={formData.group} onValueChange={(value) => handleInputChange("group", value)}>
                  <SelectTrigger>
                    <SelectValue placeholder="选择分组" />
                  </SelectTrigger>
                  <SelectContent>
                    {groups.map((group) => (
                      <SelectItem key={group} value={group}>
                        {group}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              
              <div className="space-y-2">
                <Label>收藏</Label>
                <div className="flex items-center space-x-2">
                  <Checkbox
                    id="favorite"
                    checked={formData.is_favorite}
                    onCheckedChange={(checked) => handleInputChange("is_favorite", checked)}
                  />
                  <Label htmlFor="favorite" className="text-sm font-normal">
                    添加到收藏
                  </Label>
                </div>
              </div>
            </div>

            {/* 标签管理 */}
            <div className="space-y-2">
              <Label>标签</Label>
              <div className="flex flex-wrap gap-2 mb-2">
                {formData.tags.map((tag) => (
                  <Badge key={tag} variant="secondary" className="flex items-center gap-1">
                    {tag}
                    <X
                      className="h-3 w-3 cursor-pointer"
                      onClick={() => removeTag(tag)}
                    />
                  </Badge>
                ))}
              </div>
              <div className="flex gap-2">
                <Input
                  value={newTag}
                  onChange={(e) => setNewTag(e.target.value)}
                  onKeyPress={(e) => handleKeyPress(e, addTag)}
                  placeholder="输入标签名称"
                />
                <Button type="button" onClick={addTag} size="sm">
                  <Plus className="h-4 w-4" />
                </Button>
              </div>
            </div>
          </div>

          {/* 社交账号 */}
          <div className="space-y-4">
            <h3 className="text-lg font-medium">社交账号</h3>
            
            <div className="space-y-2">
              <div className="flex flex-wrap gap-2 mb-2">
                {Object.entries(formData.social_accounts).map(([key, value]) => (
                  <Badge key={key} variant="outline" className="flex items-center gap-1">
                    {key}: {value}
                    <X
                      className="h-3 w-3 cursor-pointer"
                      onClick={() => removeSocialAccount(key)}
                    />
                  </Badge>
                ))}
              </div>
              <div className="grid grid-cols-3 gap-2">
                <Input
                  value={newSocialKey}
                  onChange={(e) => setNewSocialKey(e.target.value)}
                  placeholder="平台名称"
                />
                <Input
                  value={newSocialValue}
                  onChange={(e) => setNewSocialValue(e.target.value)}
                  placeholder="账号/链接"
                />
                <Button type="button" onClick={addSocialAccount} size="sm">
                  <Plus className="h-4 w-4" />
                </Button>
              </div>
            </div>
          </div>

          {/* 备注 */}
          <div className="space-y-2">
            <Label htmlFor="notes">备注</Label>
            <Textarea
              id="notes"
              value={formData.notes}
              onChange={(e) => handleInputChange("notes", e.target.value)}
              placeholder="请输入备注信息"
              rows={3}
            />
          </div>

          {/* 头像 */}
          <div className="space-y-2">
            <Label htmlFor="avatar">头像URL</Label>
            <Input
              id="avatar"
              value={formData.avatar}
              onChange={(e) => handleInputChange("avatar", e.target.value)}
              placeholder="请输入头像图片URL"
            />
          </div>

          <DialogFooter>
            <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
              取消
            </Button>
            <Button type="submit" disabled={loading}>
              {loading ? "保存中..." : "保存"}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  )
}
